package cn.topevery.garden.wapi.controller;


import cn.topevery.garden.framework.config.RsaKeyCache;
import cn.topevery.garden.framework.config.RsaKeyProperties;
import cn.topevery.garden.framework.util.KeyUtils;
import cn.topevery.garden.wapi.component.WfHelper;

import hw.topevery.af.entity.bo.RuntimeWorkflow;
import hw.topevery.af.entity.enums.LimitTypeEnum;
import hw.topevery.af.entity.enums.ReceiveTypeEnum;
import hw.topevery.af.entity.vo.SendActivityPara;
import hw.topevery.af.entity.vo.SendPara;
import hw.topevery.af.entity.vo.SignResult;
import hw.topevery.af.entity.vo.SingleResult;
import hw.topevery.af.runtime.WorkflowDefineManager;
import hw.topevery.af.runtime.WorkflowRuntimeManager;
import hw.topevery.basis.dal.logic.SysUserLogic;
import hw.topevery.basis.entity.po.SysUser;
import hw.topevery.framework.db.DataSourceFactory;
import hw.topevery.framework.util.SpringUtil;
import hw.topevery.framework.web.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/demo/")
public class DemoController {

    @Autowired
    SysUserLogic sysUserLogic;

    @Autowired
    WorkflowDefineManager workflowDefineManager;

    @Autowired
    WorkflowRuntimeManager workflowRuntimeManager;

    @Autowired
    WfHelper wfHelper;

    @Autowired
    private RestTemplate restTemplate;


/*    @NacosInjected
    private NamingService namingService;*/




    @Value("${hw.sso.omiUrl}")
    private String ssoOmiUrl;

    @Value("${spring.datasource.druid.max-active:10}")
    private Integer maxActive;

    @Value("${spring.datasource.druid.initial-size:5}")
    private Integer initialSize;


    @GetMapping("/index")
    public String index() {
        return "index";
    }

    @GetMapping("/getUserById")
    @Cacheable(value="user_cache_1")
    public SysUser getUserById(Integer userId) {
        System.out.println("getUserById called!");
        return sysUserLogic.getEntity(userId);
    }

    @GetMapping("/getDBConfig")
    public String getDBConfig() {

        String result = "maxActive:" + maxActive + ",initialSize:" + initialSize;


        return result;
    }

    @GetMapping("/getRunWorkflow")
    public RuntimeWorkflow getRunWorkflow(String workflowId) throws Exception {
        return workflowDefineManager.getRunWorkflow(workflowId);
    }

    @GetMapping("/startWorkflow")
    public JsonResult startWorkflow() throws Exception {
//        StartPara startPara = new StartPara();
//
//        startPara.setWfIdentifier("51CBA141-56FA-44DF-8187-277B20662460");
//        startPara.setFormUniqueId("3c7d2f93-f675-11eb-9069-00155deb0e05");
//        startPara.setReceiverId("53b39c3c-5d35-4393-aedf-b178a1da8a13");
//        startPara.setReceiverName("管理员");
//        startPara.setUserId("53b39c3c-5d35-4393-aedf-b178a1da8a13");
//        startPara.setUserName("管理员");
//        startPara.setReceiverType(ReceiveTypeEnum.USER);
//        startPara.setDate(LocalDateTime.now());
//        startPara.setLimit(10);
//        return workflowRuntimeManager.startActivity(startPara);

        return JsonResult.ok("11");
    }

    @GetMapping("/sendActivity")
    public SingleResult sendActivity(String currentInstId, String nextActivityIdentifier) throws Exception {


        String userId = "53b39c3c-5d35-4393-aedf-b178a1da8a13";
        String userName = "管理员";

        SignResult signResult = workflowRuntimeManager.signedActivity(currentInstId, userId, userName);
        System.out.println(signResult);


        SendPara sendPara = new SendPara();
        SendActivityPara sendAct = new SendActivityPara();
        sendPara.setDate(LocalDateTime.now());
        sendPara.setContent("同意。");
        sendPara.setCurrentInstId(currentInstId);
        sendPara.setUserId(userId);
        sendPara.setUserName(userName);
        sendAct.setActivityIdentifier(nextActivityIdentifier);
        sendAct.setReceiverId(userId);
        sendAct.setReceiverName(userName);
        sendAct.setReceiverType(ReceiveTypeEnum.USER);
        sendAct.setLimit(0);
        sendAct.setLimitType(LimitTypeEnum.NatureDay);
        return workflowRuntimeManager.sendActivity(sendPara, sendAct);
    }

    @GetMapping("/ssoOmiUrl")
    public String ssoOmiUrl() {
        return this.ssoOmiUrl;
    }

    //通过服务名方式调用api
    @GetMapping("/serviceCall")
    public SysUser serviceCall(Integer userId) {
        //ResponseEntity<SysUser> repRet = restTemplate.getForEntity("http://basis-wapi/demo/getUserById", SysUser.class, userId);
        //return repRet.getBody();
        System.out.println("userId:" + userId);
        try {
           /* List<Instance> instances = namingService.getAllInstances("pingxiang-wapi");

            System.out.println(instances);*/
        }catch (Exception ex){
            ex.printStackTrace();
        }

        return null;
    }


    //后端SHA-256密码加密 Hash算法不可解密 存放到数据库中的密码用这个产生
/*    @GetMapping("/getPasswd")
    public String getPasswd(String pwd) {
        PasswordEncoder encoder = new BCryptPasswordEncoder(10);
        String encoderPwd = encoder.encode(pwd);

        boolean maccheRet = encoder.matches(pwd, "$2a$10$rWnYVM613ntXjZAQYh.FUedLHYrK5e2OZSLb2MIavAjOmQiK12ETa");  //密码比对
        System.out.println("maccheRet:" + maccheRet);

        return encoderPwd;
    }*/

    //前端RSA密码解密
    @GetMapping("/rsaDecrypt")
    public String rsaDecrypt(String rsaPwd) {
        String ret = "";
        RsaKeyProperties rsaKeyProperties = SpringUtil.getBean(RsaKeyProperties.class);
        if (rsaKeyProperties.isEnable()) {
            try {
                byte[] res = KeyUtils.decrypt(RsaKeyCache.getRsaKey().getPrivate(), rsaPwd);
                ret = new String(res);

            } catch (Exception e) {
                e.printStackTrace();
                ret = e.getMessage();
            }
        }
        return ret;
    }
}
